package edu.gatech.cs2340.group7.wheresmystuffapp.model;

import edu.gatech.cs2340.group7.wheresmystuffapp.views.LoginView;

/**
 * @author tbowling3
 */
public class Security {
	private LoginView view;
	private DatabaseHelper helper;
	public Security(LoginView myView) {
		view = myView;
		helper = new DatabaseHelper(view);
	}

	/**
	 * Checks to see if username is a valid username. If the username is valid,
	 * then it calls ConfirmPassword for the given username and password. If
	 * ConfirmPassword returns true, then the last login date of the user will
	 * be updated, and if not, the login attempt for the user will be
	 * incremented by one. If you new login attempt count is 3 or greater, will
	 * call the lockAccount method for the given account. If the username is not
	 * valid, the UI will be told to re-prompt the user for a username and
	 * password preconditions: username and userEnteredPassword are strings
	 * postconditions: No changes have been to the database, except for either
	 * the last login or login attempt attributes.
	 * 
	 * @param username
	 *            The username entered by the user
	 * @param password
	 *            The password entered by the user
	 * @return
	 */
	public boolean checkLogin(String username, String userEnteredPassword) {
		Account account = helper.getAccount(username);
		if (account == null) {
			return false;
		}
		if (account.getLoginAttempts() < 3) {
			boolean correct = checkPassword(username, userEnteredPassword);
			if (correct) {
				account.setLoginAttempts(0);
				return true;
			} else {
				account.setLoginAttempts(account.getLoginAttempts() + 1);
				if (account.getLoginAttempts() == 3) {
					account.setLocked(true);
				}
				return false;
			}
		} else {
			return false;
		}
	}

	/**
	 * Checks to see if the entered password matches the one stored in the databaseSSs
	 * @param username
	 *            The username provided by the user
	 * @param userEnteredPassword
	 *            The password provided by the user
	 * @return True if the entered password matches the stored password, and
	 *         false otherwise
	 */
	private boolean checkPassword(String username,
			String userEnteredPassword) {
		Account account = helper.getAccount(username);
		if (account == null) {
			return false;
		} else {
			return account.matchPassword(userEnteredPassword);
		}
	}
}
